package nl.infodation.emr.pricingservice.ui;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;

import nl.infodation.emr.pricingservice.business.BusinessFactory;
import nl.infodation.emr.pricingservice.business.impl.RuleBusinessImpl;
import nl.infodation.emr.pricingservice.controller.Connector;
import nl.infodation.emr.pricingservice.controller.ControllerFactory;
import nl.infodation.emr.pricingservice.controller.EnvironmentController;
import nl.infodation.emr.pricingservice.controller.SystemValueRefController;
import nl.infodation.emr.pricingservice.data.DomainRuleSearchItem;
import nl.infodation.emr.pricingservice.entity.DomainListSetting;
import nl.infodation.emr.pricingservice.entity.DomainRule;
import nl.infodation.emr.pricingservice.entity.Environment;
import nl.infodation.emr.pricingservice.entity.PublishedHistory;
import nl.infodation.emr.pricingservice.entity.Role;
import nl.infodation.emr.pricingservice.entity.SystemValue;
import nl.infodation.emr.pricingservice.entity.SystemValue.TableName;
import nl.infodation.emr.pricingservice.entity.SystemValueRef;
import nl.infodation.emr.pricingservice.entity.User;
import nl.infodation.emr.pricingservice.rulegeneration.DrlFileGeneration;
import nl.infodation.emr.pricingservice.ui.component.ExplicitPagingContainer;
import nl.infodation.emr.pricingservice.ui.component.IView;
import nl.infodation.emr.pricingservice.ui.component.PagingComponent;
import nl.infodation.emr.pricingservice.ui.component.PagingModel;
import nl.infodation.emr.pricingservice.ui.page.SessionData;
import nl.infodation.emr.utility.BooleanUtil;
import nl.infodation.emr.utility.Constants;
import nl.infodation.emr.utility.DateTimeUtil;
import nl.infodation.emr.utility.StringUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.vaadin.dialogs.ConfirmDialog;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.googlecode.genericdao.search.SearchResult;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanItem;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.NativeButton;
import com.vaadin.ui.Panel;
import com.vaadin.ui.PopupDateField;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.ColumnResizeEvent;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;
import com.vaadin.ui.Window.Notification;

public class ActiveDomainRuleListView extends CustomComponent implements IView,
		ClickListener, ItemClickListener {

	private static final EntityManagerFactory EM_FACTORY = Persistence
			.createEntityManagerFactory(Constants.PRICING_PERSISTENCE_UNIT);

	private CustomLayout ActivePromotionsCustomLayout;

	private Label lblBusinessLine;

	private Label lblBusiness;

	private Button btnSwitchToPROD;

	private Button btnSwitchToPREPROD;

	private Button btnSwitchToUAT;

	private Button btnCopyToProdEnv;

	private Button btnCopyToPreProdEnv;

	private CheckBox chbCheckAll;

	private Label lblEnvironmentName;

	private DomainRuleList domainRuleList;

	private Label lblCurrentPage;

	private PagingComponent pagingComponent;

	private Button btnMarkLoaded;

	private Button btnShowLoadedRules;

	private Button btnReloadRule;

	private Button btnDeployCheckedRules;

	private Button btnDeployAllRules;

	private Button btnDeactive;

	private Button btnDuplicate;

	private Button btnAdd;

	private Button btnRollBack;

	private Button btnEdit;

	private Button btnPublishToProd;

	private Button btnPublish;

	private PopupDateField tfToDate;

	private PopupDateField tfFromDate;

	private CheckBox chbShowAllRules;

	private ComboBox cbbCountry;

	private TextField tfLanguage;

	private ComboBox cbbBusLine;

	private Button btnSearch;

	private TextField tfRuleName;

	private TextField tfPromoCode;

	private CountryCheckerPopup countryCheckerPopup;
	private DomainRulePopup domainRulePopup;
	public ConditionView conditionView;

	static private Integer CONFIRM_DEPLOY_ALL_RULES = 1;
	static private Integer CONFIRM_DEPLOY_CHECKED_RULES = 2;
	static public Integer CONFIRM_EXECUTE_SCRIPT = 3;
	
	private DomainListSetting domainSetting;
	private DomainRuleSearchItem searchItem = null;

	public void setEnableReset(boolean enable) {
		if (enable) {
			searchItem = null;
		}
	}

	private List<String> countries;

	private List<Long> checkedDomainRuleIds;

	/**
	 * The constructor should first build the main layout, set the composition
	 * root and then do any custom initialization.
	 * 
	 * The constructor will not be automatically regenerated by the visual
	 * editor.
	 */
	public ActiveDomainRuleListView(MainView parentView) {
		this.parentView = parentView;
		initLayout();
	}

	private static final Logger LOG = LoggerFactory
			.getLogger(ActiveDomainRuleListView.class);

	private static final long serialVersionUID = 1L;

	private boolean isSearching;

	// paging
	private PagingModel model = new PagingModel(0);
	private DomainRule curDomainRule = null;

	private MainView parentView;
	private boolean isCheckAll = Boolean.FALSE;

	@Override
	public void initLayout() {
		buildMainLayout();
		// Separate this reference assignment to enable design view support for
		// Vaadin
		// because of autogenerated buildMainLayout method
		this.domainRuleList.setParentView(this);
		setFormatDateField();
		resetField();
		configureEnvironments();
		setCaptionForMultiLanguage();
		addListener();
		initialModelPaging();
		updatePageNumber();
		initialFunctionClear();
		applyTemporaryPatch();
		setOptionForBusLine();
		setOptionForCountry();
		isSearching = Boolean.FALSE;
		searchItem = null;
		this.setCompositionRoot(ActivePromotionsCustomLayout);
	}

	private DomainListSetting getDomainListSetting() {
		DomainListSetting chooseDomain = new DomainListSetting();
		User currentUser = new User();
		currentUser.setUsername(SessionData.getUsername());
		chooseDomain.setUser(currentUser);
		List<DomainListSetting> domainListSettings = ControllerFactory
				.getDomainSettingController().findByEntity(chooseDomain);

		if (null == domainListSettings || domainListSettings.isEmpty()) {
			DomainListSetting domainListSetting = ControllerFactory
					.getDomainSettingController().getObjectById(
							Constants.DOMAIN_RULE_LIST_SETTING_ID_DEFAULT);

			User user = (User) ControllerFactory.getUserController()
					.getObjectById(SessionData.getUsername());
			domainListSetting.setUser(user);
			domainListSetting.setIsDefault(Boolean.FALSE);
			domainListSetting.setSettingId(null);

			return domainListSetting;
		} else {
			return domainListSettings.get(0);
		}
	}

	@SuppressWarnings("rawtypes")
	private void setOptionForBusLine() {
		cbbBusLine.setNullSelectionAllowed(Boolean.FALSE);
		cbbBusLine.removeAllItems();

		if (SessionData.isSuperAdmin()) {
			cbbBusLine.addItem(Constants.ALL_FOR_SEARCH);
			List<BeanItem> beans = ControllerFactory.getRoleController()
					.getPaginationList(1, Integer.MAX_VALUE);
			if (beans != null) {
				for (BeanItem item : beans) {
					Role role = (Role) item.getBean();
					cbbBusLine.addItem(role.getRoleName());
				}
			}
		} else {
			String roleName = SessionData.getRoleName();
			cbbBusLine.addItem(roleName);
		}

		if (StringUtil.isEmptyOrBlank((String) cbbBusLine.getValue())) {
			// choose first item
			cbbBusLine.setValue(cbbBusLine.getItemIds().iterator().next());
		}
	}

	@SuppressWarnings("rawtypes")
	private void setOptionForCountry() {
		cbbCountry.setNullSelectionAllowed(Boolean.FALSE);
		cbbCountry.removeAllItems();

		cbbCountry.addItem(Constants.ALL_FOR_SEARCH);
		if (SessionData.isNormalAdmin() || SessionData.isSuperAdmin()) {

			SystemValue systemValue = new SystemValue();
			systemValue.setSystemName(TableName.COUNTRY);
			List<BeanItem> countries = ControllerFactory
					.getSystemValueController().getPaginationByCriteria(
							systemValue, 1, Integer.MAX_VALUE);

			for (BeanItem beanItem : countries) {
				SystemValue country = (SystemValue) beanItem.getBean();
				cbbCountry.addItem(country.getSystemCode().toUpperCase());
			}
		} else {
			for (SystemValue country : SessionData.getCountriesToSee()) {
				cbbCountry.addItem(country.getSystemCode().toUpperCase());
			}
		}

		if (StringUtil.isEmptyOrBlank((String) cbbCountry.getValue())) {
			// choose first item
			cbbCountry.setValue(cbbCountry.getItemIds().iterator().next());
		}
	}

	/**
	 * temporary fixes from customer requirements can be changed rapidly
	 */
	private void applyTemporaryPatch() {
	}

	private void initialFunctionClear() {
		selectFirstItem();
		if (!isCheckAll) {
			DomainRuleList.getActiveList().clear();
		}
		setEnableCheckedRule(DomainRuleList.getActiveList().size() > 0);
	}

	@SuppressWarnings("rawtypes")
	public void selectFirstItem() {
		if (domainRuleList.getItemCount() > 0) {
			domainRuleList.select(0);
			BeanItem bean = (BeanItem) domainRuleList.getItem(0);
			curDomainRule = (DomainRule) bean.getBean();
		} else {
			setEnableChosenRule(Boolean.FALSE);
		}
	}

	public void setCurDomainRule(DomainRule curDomainRule) {
		this.curDomainRule = curDomainRule;
	}

	public DomainRule getCurDomainRule() {
		return curDomainRule;
	}

	private void initialModelPaging() {
		model.addPropertyChangeListener("currentPage",
				new PropertyChangeListener() {
					public void propertyChange(final PropertyChangeEvent evt) {
						if (isSearching) {
							DomainRuleSearchItem searchItem = prepareSearchItem();
							updateListBySearching(model.getCurrentPage(),
									searchItem);
						} else {
							DomainRuleSearchItem searchItem = new DomainRuleSearchItem();
							searchItem.setTodayDate(new Date());
							updateListBySearching(model.getCurrentPage(),
									searchItem);
						}
					}
				});
		pagingComponent.setModel(model);
		updatePageNumber();
	}

	public void setBinding(Property envProperty) {
		lblEnvironmentName.setPropertyDataSource(envProperty);
	}

	private boolean hasEnvironment(int envId) {
		return ((EnvironmentController) ControllerFactory
				.getEnvironmentController()).findEnvironment(envId) != null;
	}

	private void configureEnvironments() {
		if (!hasEnvironment(Constants.UAT_ENVIROMENT)) {
			btnSwitchToUAT.setEnabled(Boolean.FALSE);
		} else {
			navigateToUatEnv();
		}

		if (!hasEnvironment(Constants.PRE_PROD_ENVIROMENT)) {
			btnSwitchToPREPROD.setEnabled(Boolean.FALSE);
		} else if (!hasEnvironment(Constants.UAT_ENVIROMENT)) {
			navigateToPreProdEnv();
		}

		if (!hasEnvironment(Constants.PROD_ENVIROMENT)) {
			btnSwitchToPROD.setEnabled(Boolean.FALSE);
		}

		if (SessionData.isSuperAdmin()) {
			ActivePromotionsCustomLayout.addComponent(initButtonCustomLayout(),
					"lcShowOption");
		}
	}

	private void navigateToUatEnv() {
		SessionData.setEnvironment(Constants.UAT_ENVIROMENT);
		this.lblEnvironmentName.setValue(SessionData.getI18N().getMessage(
				Constants.UAT_ENVIROMENT_MESSAGE));

		boolean preProd = hasEnvironment(Constants.PRE_PROD_ENVIROMENT);
		boolean prod = hasEnvironment(Constants.PROD_ENVIROMENT);

		btnSwitchToUAT.setEnabled(Boolean.FALSE);
		btnSwitchToPREPROD.setEnabled(preProd);
		btnSwitchToPROD.setEnabled(prod);
		btnCopyToPreProdEnv.setEnabled(preProd);
		btnCopyToProdEnv.setEnabled(prod);
		btnPublishToProd.setEnabled(Boolean.FALSE);
	}

	private void navigateToPreProdEnv() {
		SessionData.setEnvironment(Constants.PRE_PROD_ENVIROMENT);
		this.lblEnvironmentName.setValue(SessionData.getI18N().getMessage(
				Constants.PRE_PROD_ENVIROMENT_MESSAGE));

		boolean uat = hasEnvironment(Constants.UAT_ENVIROMENT);
		boolean prod = hasEnvironment(Constants.PROD_ENVIROMENT);

		btnSwitchToUAT.setEnabled(uat);
		btnSwitchToPREPROD.setEnabled(Boolean.FALSE);
		btnSwitchToPROD.setEnabled(prod);
		btnCopyToPreProdEnv.setEnabled(Boolean.FALSE);
		btnCopyToProdEnv.setEnabled(prod);
		btnPublishToProd.setEnabled(Boolean.TRUE);
	}

	private void navigateToProdEnv() {
		SessionData.setEnvironment(Constants.PROD_ENVIROMENT);
		this.lblEnvironmentName.setValue(SessionData.getI18N().getMessage(
				Constants.PROD_ENVIROMENT_MESSAGE));

		boolean uat = hasEnvironment(Constants.UAT_ENVIROMENT);
		boolean preProd = hasEnvironment(Constants.PRE_PROD_ENVIROMENT);

		btnSwitchToUAT.setEnabled(uat);
		btnSwitchToPREPROD.setEnabled(preProd);
		btnSwitchToPROD.setEnabled(Boolean.FALSE);
		btnCopyToPreProdEnv.setEnabled(preProd);
		btnCopyToProdEnv.setEnabled(Boolean.FALSE);
		btnPublishToProd.setEnabled(Boolean.FALSE);
	}

	private void setCaptionForMultiLanguage() {
		tfPromoCode.setCaption(SessionData.getI18N().getMessage(
				Constants.PROMOTION_CODE_TEXTFIELD));
		tfRuleName.setCaption(SessionData.getI18N().getMessage(
				Constants.RULE_NAME_TEXTFIELD));
		cbbBusLine.setCaption(SessionData.getI18N().getMessage(
				Constants.BUS_LINE_TEXTFIELD));
		tfLanguage.setCaption(SessionData.getI18N().getMessage(
				Constants.LANGUAGE_TEXTFIELD));
		btnSearch.setCaption(SessionData.getI18N().getMessage(
				Constants.SEARCH_BUTTON));
		Label lb = new Label(SessionData.getI18N().getMessage(
				Constants.PUBLISH_BUTTON));
		lb.setWidth("20px");
		ActivePromotionsCustomLayout.addComponent(lb, "lcTipPublish");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.PUBLISH2PROD_BUTTON)),
				"lcTipPublishToProd");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.LOAD_BUTTON)), "lcTipLoad");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.ADD_BUTTON)), "lcTipAddNew");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.DUPLICATE_BUTTON)),
				"lcTipDuplicateRule");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.DEACTIVE_BUTTON)),
				"lcTipDeactive");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.ROLLBACK_BUTTON)),
				"lcTipRollBack");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.SHOW_LOADED_RULES_BUTTON)),
				"lcTipShowLoadedRules");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.SWITCH_TO_PREPROD_BUTTON)),
				"lcTipSwitchToPreProd");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.SWITCH_TO_PROD_BUTTON)),
				"lcTipSwitchToProd");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.SWITCH_TO_UAT_BUTTON)),
				"lcTipSwitchToUAT");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.SWITCH_TO_PREPROD_BUTTON)),
				"lcTipCopyToPreProdEnv");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.SWITCH_TO_PROD_BUTTON)),
				"lcTipCopyToProdEnv");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.DEPLOY_ALL_RULES_BUTTON)),
				"lcTipDeployAllRules");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.DEPLOY_CHECKED_RULES_BUTTON)),
				"lcTipDeployCheckedRules");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.RELOAD_BUTTON)), "lcTipReload");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.MARK_LOADED_RULES_BUTTON)),
				"lcTipMarkLoaded");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.SCRIPT_BUTTON)),
				"lcTipExecuteScript");
		ActivePromotionsCustomLayout.addComponent(new Label(SessionData
				.getI18N().getMessage(Constants.FORM_FILTER)), "lbFilter");

		lblEnvironmentName.setValue(SessionData.getI18N().getMessage(
				Constants.ENVIRONMENT_LABLE));
		cbbCountry.setCaption(SessionData.getI18N().getMessage(
				Constants.COUNTRY_TEXTFIELD));
		tfFromDate.setCaption(SessionData.getI18N().getMessage(
				Constants.FROM_DATE_TEXTFIELD));
		tfToDate.setCaption(SessionData.getI18N().getMessage(
				Constants.TO_DATE_TEXTFIELD));
		chbShowAllRules.setCaption(SessionData.getI18N().getMessage(
				Constants.SHOW_ALL_RULES_CHECKBOX));

		chbCheckAll.setCaption(SessionData.getI18N().getMessage(
				Constants.CHECK_ALL_CHECKBOX));
		lblBusiness.setValue(SessionData.getI18N().getMessage(
				Constants.BUSINESS_LABEL));
	}

	private void updatePageNumber() {
		lblCurrentPage.setValue(SessionData.getI18N().getMessage(
				Constants.CURRENT_PAGE_VALUE)
				+ model.getCurrentPage());
	}

	@SuppressWarnings("serial")
	private void addListener() {
		domainRuleList.addListener((ItemClickListener) this);
		btnPublish.addListener((ClickListener) this);
		btnPublishToProd.addListener((ClickListener) this);
		btnEdit.addListener((ClickListener) this);
		btnAdd.addListener((ClickListener) this);
		btnRollBack.addListener((ClickListener) this);
		btnSearch.addListener((ClickListener) this);
		btnDuplicate.addListener((ClickListener) this);
		btnDeactive.addListener((ClickListener) this);
		btnSwitchToUAT.addListener((ClickListener) this);
		btnSwitchToPREPROD.addListener((ClickListener) this);
		btnSwitchToPROD.addListener((ClickListener) this);
		btnCopyToPreProdEnv.addListener((ClickListener) this);
		btnCopyToProdEnv.addListener((ClickListener) this);
		btnDeployCheckedRules.addListener((ClickListener) this);
		btnDeployAllRules.addListener((ClickListener) this);
		btnReloadRule.addListener((ClickListener) this);
		btnMarkLoaded.addListener((ClickListener) this);
		btnShowLoadedRules.addListener((ClickListener) this);

		chbCheckAll.addListener((ClickListener) this);
		chbCheckAll.setImmediate(Boolean.TRUE);

		lblEnvironmentName.setImmediate(Boolean.TRUE);
		lblEnvironmentName.addListener(new ValueChangeListener() {
			private static final long serialVersionUID = 1L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				Property p = event.getProperty();
				if (p.getValue().equals(
						SessionData.getI18N().getMessage(
								Constants.UAT_ENVIROMENT_MESSAGE))) {

				} else if (p.getValue().equals(
						SessionData.getI18N().getMessage(
								Constants.PRE_PROD_ENVIROMENT_MESSAGE))) {

				} else if (p.getValue().equals(
						SessionData.getI18N().getMessage(
								Constants.PROD_ENVIROMENT_MESSAGE))) {
				}
			}
		});

		domainRuleList.addListener(new Table.ColumnResizeListener() {
			public void columnResize(ColumnResizeEvent event) {
				int width = event.getCurrentWidth();
				ControllerFactory.getDomainSettingController().saveObject(
						settingDomain(event, width));
			}
		});
	}

	private DomainListSetting settingDomain(ColumnResizeEvent event, int width) {

		if (event.getPropertyId().toString().equals("choise")) {
			domainSetting.setChoise(width);
		} else if (event.getPropertyId().toString().equals("ruleId")) {
			domainSetting.setRuleId(width);
		} else if (event.getPropertyId().toString().equals("ruleName")) {
			domainSetting.setRuleName(width);
		} else if (event.getPropertyId().toString().equals("description")) {
			domainSetting.setDescription(width);
		} else if (event.getPropertyId().toString().equals("busLine")) {
			domainSetting.setBusLine(width);
		} else if (event.getPropertyId().toString().equals("country")) {
			domainSetting.setCountry(width);
		} else if (event.getPropertyId().toString().equals("beginDate")) {
			domainSetting.setBeginDate(width);
		} else if (event.getPropertyId().toString().equals("endDate")) {
			domainSetting.setEndDate(width);
		}

		return domainSetting;
	}

	private void resetField() {
		chbCheckAll.setValue(null);
		cbbBusLine.setValue(Constants.ALL_FOR_SEARCH);
		cbbCountry.setValue(Constants.ALL_FOR_SEARCH);
		tfRuleName.setValue("");
		tfPromoCode.setValue("");
		tfLanguage.setValue("");

		tfFromDate.setValue(null);
		tfToDate.setValue(null);

		chbShowAllRules.setValue(Boolean.FALSE);
		lblBusinessLine.setValue(getBusinessLineValue());
	}

	private String getBusinessLineValue() {
		// Process for role
		String roleName = SessionData.getRoleName();
		if (SessionData.isSuperAdmin()) {
			return SessionData.getDeploymentRoleName();
		}
		// PROVEA or AFM
		return roleName;
	}

	@Override
	public void reload() {
		LOG.info(DateTimeUtil.getNow() + "Reload overview page");
		if (searchItem == null) {
			isSearching = Boolean.FALSE;
			resetField();

			DomainRuleSearchItem searchItem = new DomainRuleSearchItem();
			searchItem.setTodayDate(new Date());
			updateListBySearching(PagingModel.FIRST_PAGE, searchItem);
		} else {
			// Saving filters when browsing between rules
			executeSearch(searchItem, model.getCurrentPage());
		}

		initialFunctionClear();
	}

	private String getWebServiceAddressForEnvironmentAndBusiness() {
		String address = null;

		EntityManager entityManager = null;
		try {
			entityManager = EM_FACTORY.createEntityManager();

			Connector connector = new Connector();
			Environment env = (Environment) ControllerFactory
					.getEnvironmentController().getObjectById(
							SessionData.getEnvironment());
			int envId = env.getEnvironmentId();

			String roleName = getRoleConfig();

			if (envId == Constants.UAT_ENVIROMENT
					&& roleName.equals(Constants.AFM_ROLE)) {
				address = connector.getConfig(Constants.UAT_WS_ADDRESS_AFM,
						entityManager);

			} else if (envId == Constants.PRE_PROD_ENVIROMENT
					&& roleName.equals(Constants.AFM_ROLE)) {
				address = connector.getConfig(Constants.PREPROD_WS_ADDRESS_AFM,
						entityManager);

			} else if (envId == Constants.PROD_ENVIROMENT
					&& roleName.equals(Constants.AFM_ROLE)) {
				address = connector.getConfig(Constants.PROD_WS_ADDRESS_AFM,
						entityManager);

			} else if (envId == Constants.UAT_ENVIROMENT
					&& roleName.equals(Constants.PROVEA_ROLE)) {
				address = connector.getConfig(Constants.UAT_WS_ADDRESS_PROVEA,
						entityManager);

			} else if (envId == Constants.PRE_PROD_ENVIROMENT
					&& roleName.equals(Constants.PROVEA_ROLE)) {
				address = connector.getConfig(
						Constants.PREPROD_WS_ADDRESS_PROVEA, entityManager);

			} else if (envId == Constants.PROD_ENVIROMENT
					&& roleName.equals(Constants.PROVEA_ROLE)) {
				address = connector.getConfig(Constants.PROD_WS_ADDRESS_PROVEA,
						entityManager);
			}
		} finally {
			if (entityManager != null && entityManager.isOpen()) {
				entityManager.close();
			}
		}

		return address;
	}

	private String getRoleConfig() {
		String roleName = SessionData.getRoleName();

		if (SessionData.isSuperAdmin()) {
			if (parentView.getBusinessChosen() != null) {
				roleName = parentView.getBusinessChosen();
			}
		}

		return roleName;
	}

	private String getRulePathForEnvironmentAndBusiness() {
		String filePath = null;

		EntityManager entityManager = null;
		try {
			entityManager = EM_FACTORY.createEntityManager();

			Connector connector = new Connector();
			Environment env = (Environment) ControllerFactory
					.getEnvironmentController().getObjectById(
							SessionData.getEnvironment());
			int envId = env.getEnvironmentId();

			String roleName = getRoleConfig();

			if (envId == Constants.UAT_ENVIROMENT
					&& roleName.equals(Constants.AFM_ROLE)) {
				filePath = connector.getConfig(Constants.UAT_RULE_PATH_AFM,
						entityManager);
			} else if (envId == Constants.PRE_PROD_ENVIROMENT
					&& roleName.equals(Constants.AFM_ROLE)) {
				filePath = connector.getConfig(Constants.PREPROD_RULE_PATH_AFM,
						entityManager);
			} else if (envId == Constants.PROD_ENVIROMENT
					&& roleName.equals(Constants.AFM_ROLE)) {
				filePath = connector.getConfig(Constants.PROD_RULE_PATH_AFM,
						entityManager);
			} else if (envId == Constants.UAT_ENVIROMENT
					&& roleName.equals(Constants.PROVEA_ROLE)) {
				filePath = connector.getConfig(Constants.UAT_RULE_PATH_PROVEA,
						entityManager);
			} else if (envId == Constants.PRE_PROD_ENVIROMENT
					&& roleName.equals(Constants.PROVEA_ROLE)) {
				filePath = connector.getConfig(
						Constants.PREPROD_RULE_PATH_PROVEA, entityManager);
			} else if (envId == Constants.PROD_ENVIROMENT
					&& roleName.equals(Constants.PROVEA_ROLE)) {
				filePath = connector.getConfig(Constants.PROD_RULE_PATH_PROVEA,
						entityManager);
			}
		} finally {
			if (entityManager != null && entityManager.isOpen()) {
				entityManager.close();
			}
		}

		return filePath;
	}

	private void executeLoad() {
		if (curDomainRule == null) {
			getWindow().showNotification(
					SessionData.getI18N().getMessage(
							Constants.NO_PROMOTION_SELECTION_MESSAGE),
					Notification.TYPE_WARNING_MESSAGE);
			return;
		}
		parentView.showDetail();
		parentView.setDetailView(curDomainRule, true);
	}

	private void executeAdd() {

		DomainRule newRule = new DomainRule();

		Environment env = (Environment) ControllerFactory
				.getEnvironmentController().getObjectById(
						SessionData.getEnvironment());
		newRule.setEnvironment(env);
		parentView.showDetail();
		parentView.setDetailView(newRule, false);
		conditionView = new ConditionView();
		conditionView.setchbPromotionCodeIsCheck(Boolean.FALSE);
		conditionView.setChbXofFamilyCheck(Boolean.FALSE);
	}

	private void executeDuplicate() {
		parentView.showDetail();

		if (curDomainRule == null) {
			getWindow().showNotification(
					SessionData.getI18N().getMessage(
							Constants.NO_PROMOTION_SELECTION_MESSAGE),
					Notification.TYPE_WARNING_MESSAGE);
			return;
		}

		// The id is null
		DomainRule newDomainRule = curDomainRule.copyWithoutKey();

		Environment env = (Environment) ControllerFactory
				.getEnvironmentController().getObjectById(
						Constants.UAT_ENVIROMENT);
		newDomainRule.setEnvironment(env);

		parentView.setDetailView(newDomainRule, false);
	}

	private void executeRemove() {
		if (DomainRuleList.getActiveList().isEmpty()) {
			getWindow().showNotification(
					SessionData.getI18N().getMessage(
							Constants.NO_PROMOTION_CHOICE_MESSAGE),
					Notification.TYPE_WARNING_MESSAGE);
			return;
		}

		List<DomainRule> domainRules = BusinessFactory.getRuleBusiness()
				.findRulesByIDs(DomainRuleList.getActiveList());

		Iterator<DomainRule> iterator = domainRules.iterator();
		while (iterator.hasNext()) {
			iterator.next().setPromotionActive(Boolean.FALSE);
		}

		// Show result message
		if (BusinessFactory.getRuleBusiness().saveRules(domainRules)) {
			getWindow().showNotification(
					SessionData.getI18N().getMessage(
							Constants.DEACTIVE_MESSAGE_SUCCESS),
					Notification.TYPE_WARNING_MESSAGE);
		} else {
			getWindow().showNotification(
					SessionData.getI18N().getMessage(
							Constants.DEACTIVE_MESSAGE_FAIL),
					Notification.TYPE_WARNING_MESSAGE);
		}
		ReloadSearching();
	}

	private void confirmAction(String messageKey,
			ConfirmDialog.Listener listener) {
		String message = SessionData.getI18N().getMessage(messageKey);
		String confirm_yes = SessionData.getI18N().getMessage(
				Constants.CONFIRM_YES);
		String confirm_no = SessionData.getI18N().getMessage(
				Constants.CONFIRM_NO);
		ConfirmDialog.show(getWindow(), "", message, confirm_yes, confirm_no,
				listener);
	}

	@SuppressWarnings("serial")
	public void confirmDeploy(final Integer type) {

		// confirm dialog
		String message = SessionData.getI18N().getMessage(
				Constants.CONFIRM_DEPLOY_RULES_MESSAGE);
		String confirm_yes = SessionData.getI18N().getMessage(
				Constants.CONFIRM_YES);
		String confirm_no = SessionData.getI18N().getMessage(
				Constants.CONFIRM_NO);

		ConfirmDialog.show(getWindow(), "", message, confirm_yes, confirm_no,
				new ConfirmDialog.Listener() {
					public void onClose(ConfirmDialog dialog) {
						getConfirmDialogFeedback(dialog.isConfirmed(), type);
					}
				});
	}

	private void getConfirmDialogFeedback(Boolean isUserConfirmed, Integer cType) {
		if (isUserConfirmed) {
			if (cType.equals(CONFIRM_DEPLOY_ALL_RULES)) {
				executeDeployAllRules();
			} else if (cType.equals(CONFIRM_DEPLOY_CHECKED_RULES)) {
				executeDeployCheckedRules(Boolean.TRUE);
			} else if (cType.equals(CONFIRM_EXECUTE_SCRIPT)) {
				executeScript(getCountriesFromCountryCheckerList());
			} else {
				LOG.info("Don't deploy any rule or excute any script.");
			}
		} else {
			LOG.info("Don't deploy any rule or excute any script.");
		}
	}

	private void executeDeployAllRules() {
		List<DomainRule> domainRules = BusinessFactory.getRuleBusiness()
				.findRulesByBusLine(getRoleConfig());
		deployRules(domainRules, Boolean.TRUE);
	}

	private boolean executeDeployCheckedRules(boolean interactive) {

		List<Long> activeList = DomainRuleList.getActiveList();

		if (activeList.size() == 0) {
			getWindow().showNotification(
					SessionData.getI18N().getMessage(
							Constants.NO_PROMOTION_CHOICE_MESSAGE),
					Notification.TYPE_WARNING_MESSAGE);
			return Boolean.FALSE;
		}

		List<DomainRule> domainRules = BusinessFactory.getRuleBusiness()
				.findRulesByIDs(activeList);

		return deployRules(domainRules, interactive);
	}

	private String getRuleFileFull(String countryCode) {
		String file = getRulePathForEnvironmentAndBusiness();
		String dynamic = Constants.DYNAMIC_COUNTRY_CODE;
		String filePath = file.replaceAll(dynamic,
				countryCode.toLowerCase());
		return filePath;
	}
	
	private boolean deployRules(List<DomainRule> domainRules,
			boolean interactive) {

		String filePath = "";

		try {
			DrlFileGeneration generation = new DrlFileGeneration();

			for (Entry<String, List<DomainRule>> entry : getRuleListByCountry(
					domainRules).entrySet()) {
				List<DomainRule> rulesByCountry = entry.getValue();
				String countryCode = entry.getKey().toLowerCase();

				generation.clearAllRules();
				// controller for back up rules
				List<PublishedHistory> histories = new ArrayList<>();
				for (DomainRule domainRule : rulesByCountry) {
					generation.defineRule(domainRule);
					// create backup rule objects
					histories.add(createRuleHistory(domainRule));
				}
				ControllerFactory.getPublishedHistoryController().save(
						histories);

				// Get rule path in database
				// following condition of environment and business.
				filePath = getRuleFileFull(countryCode);

				if (filePath != null) {
					String packagePrefix = this.getPackagePrefix();
					generation.generateDrlFile(filePath, packagePrefix != null
							&& packagePrefix.length() > 0 ? packagePrefix
							: "ch.provea", countryCode, this);
				}
				if (interactive) {
					getWindow().showNotification(
							SessionData.getI18N().getMessage(
									Constants.DEPLOY_RULE_SUCCESS));
				}
			}
			return Boolean.TRUE;
		} catch (IOException e) {
			if (interactive) {
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.DEPLOY_RULE_FAIL));
			}
			LOG.error("Error when deploy rules to " + filePath, e);
		}
		return Boolean.FALSE;
	}

	private String getBusinessLineFromLoginedAccount() {
		String businessLine = "";

		if (SessionData.isSuperAdmin()) {
			businessLine = SessionData.getDeploymentRoleName();
		} else {
			businessLine = SessionData.getRoleName();
		}

		return businessLine.toLowerCase();
	}

	private String getPackagePrefix() {
		EntityManager entityManager = null;
		String packagePrefix = null;
		try {
			entityManager = EM_FACTORY.createEntityManager();
			Connector connector = new Connector();
			String rulePackageKey = Constants.RULEPACKAGEPREFIX + "."
					+ getBusinessLineFromLoginedAccount();
			packagePrefix = connector.getConfig(rulePackageKey, entityManager);
		} finally {
			if (entityManager != null && entityManager.isOpen()) {
				entityManager.close();
			}
		}
		return packagePrefix;
	}

	private Map<String, List<DomainRule>> getRuleListByCountry(
			List<DomainRule> domainRules) {
		Map<String, List<DomainRule>> result = new HashMap<String, List<DomainRule>>();
		if (null == domainRules || domainRules.isEmpty()) {
			return result;
		}

		for (DomainRule rule : domainRules) {
			String countryCode = rule.getCountry().toUpperCase();
			List<DomainRule> ruleList = result.get(countryCode);
			if (null == ruleList) {
				ruleList = new ArrayList<DomainRule>();
				result.put(countryCode, ruleList);
			}

			ruleList.add(rule);
		}

		return result;
	}

	private PublishedHistory createRuleHistory(DomainRule domainRule) {
		PublishedHistory pHistory = new PublishedHistory();

		pHistory.setDomainRule(domainRule);
		Calendar cal = Calendar.getInstance();
		pHistory.setPublishedDate(cal.getTime());

		return pHistory;
	}

	private void executeSwitchToUAT() {
		navigateToUatEnv();
		this.reload();
		getWindow().showNotification(
				SessionData.getI18N().getMessage(
						Constants.UAT_ENVIROMENT_MESSAGE),
				Notification.TYPE_WARNING_MESSAGE);
	}

	private void executeSwitchToPREPROD() {
		navigateToPreProdEnv();
		this.reload();
		getWindow().showNotification(
				SessionData.getI18N().getMessage(
						Constants.PRE_PROD_ENVIROMENT_MESSAGE),
				Notification.TYPE_WARNING_MESSAGE);
	}

	private void executeSwitchToPROD() {
		navigateToProdEnv();
		this.reload();
		getWindow().showNotification(
				SessionData.getI18N().getMessage(
						Constants.PROD_ENVIROMENT_MESSAGE),
				Notification.TYPE_WARNING_MESSAGE);
	}

	private void executeCopyToPreProdEnv() {
		if (BusinessFactory.getRuleBusiness().copyToEnvironment(
				getBusinessLineValue(), SessionData.getRoleName(),
				Constants.PRE_PROD_ENVIROMENT, Boolean.FALSE,
				DomainRuleList.getActiveList())) {
			getWindow().showNotification(
					SessionData.getI18N().getMessage(
							Constants.SUCCESSFULLY_MESSAGE),
					Notification.TYPE_WARNING_MESSAGE);
		} else {
			getWindow().showNotification(
					SessionData.getI18N().getMessage(Constants.FAILED_MESSAGE),
					Notification.TYPE_WARNING_MESSAGE);
		}
	}

	private boolean executeCopyToProdEnv(boolean interactive, boolean clean) {
		if (BusinessFactory.getRuleBusiness().copyToEnvironment(
				getBusinessLineValue(), SessionData.getRoleName(),
				Constants.PROD_ENVIROMENT, clean,
				DomainRuleList.getActiveList())) {
			if (interactive) {
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.SUCCESSFULLY_MESSAGE),
						Notification.TYPE_WARNING_MESSAGE);
			}
			return Boolean.TRUE;
		} else if (interactive) {
			getWindow().showNotification(
					SessionData.getI18N().getMessage(Constants.FAILED_MESSAGE),
					Notification.TYPE_WARNING_MESSAGE);
		}
		return Boolean.FALSE;
	}

	public boolean executeReloadRule(List<String> countries) {
		String address = getWebServiceAddressForEnvironmentAndBusiness();
		if (address != null) {
			// send request here
			try {
				URI uriPost = new URI(address);

				String packagePrefix = this.getPackagePrefix();
				String prefixParts[] = packagePrefix.split("\\.");
				HttpPost postRequest = new HttpPost(uriPost);
				DefaultHttpClient client = new DefaultHttpClient();
				String body = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.pricing.webservice."
						+ prefixParts[1]
						+ "."
						+ prefixParts[0]
						+ "/\">"
						+ "<soapenv:Header/>"
						+ "<soapenv:Body>"
						+ "<ser:reload>" + "<type>RELOAD</type>";
				body += "<countryCodeList>";
				if (null != countries && !countries.isEmpty()) {
					for (String country : countries) {
						body += "<item>" + country + "</item>";
					}
				}
				body += "</countryCodeList>";
				body += "</ser:reload>" + "</soapenv:Body>"
						+ "</soapenv:Envelope>";

				StringEntity soapEntiry = new StringEntity(body,
						HTTP.DEFAULT_CONTENT_CHARSET);

				postRequest.setEntity(soapEntiry);
				HttpResponse response = client.execute(postRequest);

				if (response.getStatusLine().getStatusCode() == 200) {
					InputStream responseIS = response.getEntity().getContent();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(responseIS));
					String line = reader.readLine();
					while (line != null) {
						getWindow().showNotification(
								SessionData.getI18N().getMessage(
										Constants.SUCCESS_RELOAD_WS));
						LOG.info("SOAP RELOAD RESPONSE:" + line);
						line = reader.readLine();
					}
					return Boolean.TRUE;
				} else {
					getWindow().showNotification(
							SessionData.getI18N().getMessage(
									Constants.ERROR_RELOAD_WS));
					return Boolean.FALSE;
				}
			} catch (URISyntaxException uriSyntaxException) {
				LOG.warn(String.format(
						"Web service address(\"%s\") is invalid", address),
						uriSyntaxException);
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.WS_ADDRESS_INVALID));
			} catch (UnsupportedEncodingException unsupportedEncodingException) {
				LOG.error("The charset is not supported",
						unsupportedEncodingException);
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.ERROR_RELOAD_WS));
			} catch (ClientProtocolException clientProtocolException) {
				LOG.error("Error sending request to web service",
						clientProtocolException);
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.ERROR_RELOAD_WS));
			} catch (IOException | IllegalStateException e) {
				LOG.error("Failed reading response content", e);
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.ERROR_RELOAD_WS));
			}
		}
		return Boolean.FALSE;
	}

	public int getLoadedRulesPublishing(List<String> countries) {
		String address = getWebServiceAddressForEnvironmentAndBusiness();
		int numberOfRules = 0;
		if (address != null) {
			try {
				URI uriPost = new URI(address);
				String packagePrefix = this.getPackagePrefix();
				String prefixParts[] = packagePrefix.split("\\.");
				HttpPost postRequest = new HttpPost(uriPost);
				DefaultHttpClient client = new DefaultHttpClient();
				String body = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.pricing.webservice."
						+ prefixParts[1]
						+ "."
						+ prefixParts[0]
						+ "/\">"
						+ "<soapenv:Header/>"
						+ "<soapenv:Body>"
						+ "<ser:getLoadedRules>"
						+ "<type>LOADEDRULES</type>"
						+ "<countryCodeList>" + "<item>\"\"</item>";

				for (String country : countries) {
					body += "<item>" + country + "</item>";
				}

				body += "</countryCodeList>" + "</ser:getLoadedRules>"
						+ "</soapenv:Body>" + "</soapenv:Envelope>";
				StringEntity soapEntiry;
				soapEntiry = new StringEntity(body, HTTP.UTF_8);

				postRequest.setEntity(soapEntiry);
				HttpResponse response = client.execute(postRequest);
				InputStream responseIS = response.getEntity().getContent();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(responseIS));
				String line = reader.readLine();
				if (StringUtils.isNotEmpty(line)) {
					List<nl.infodation.emr.pricingservice.data.Item> items = getItemValues(line);
					numberOfRules = items.size();
				}
			} catch (URISyntaxException uriSyntaxException) {
				LOG.warn(String.format(
						"Web service address(\"%s\") is invalid", address),
						uriSyntaxException);
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.WS_ADDRESS_INVALID));
			} catch (UnsupportedEncodingException unsupportedEncodingException) {
				LOG.error("The charset is not supported",
						unsupportedEncodingException);
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.ERROR_RELOAD_WS));
			} catch (ClientProtocolException clientProtocolException) {
				LOG.error("Error sending request to web service",
						clientProtocolException);
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.ERROR_RELOAD_WS));
			} catch (IOException | SOAPException e) {
				LOG.error("Failed reading response content", e);
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.ERROR_RELOAD_WS));
			}
		}
		return numberOfRules;
	}

	public boolean executeShowLoadedRules(boolean markLoaded,
			boolean interactive, List<String> countries) {
		String address = getWebServiceAddressForEnvironmentAndBusiness();
		if (address != null) {
			// send request here
			try {
				URI uriPost = new URI(address);
				String packagePrefix = this.getPackagePrefix();
				String prefixParts[] = packagePrefix.split("\\.");
				HttpPost postRequest = new HttpPost(uriPost);
				DefaultHttpClient client = new DefaultHttpClient();
				String body = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.pricing.webservice."
						+ prefixParts[1]
						+ "."
						+ prefixParts[0]
						+ "/\">"
						+ "<soapenv:Header/>"
						+ "<soapenv:Body>"
						+ "<ser:getLoadedRules>"
						+ "<type>LOADEDRULES</type>"
						+ "<countryCodeList>" + "<item>\"\"</item>";

				for (String country : countries) {
					body += "<item>" + country + "</item>";
				}

				body += "</countryCodeList>" + "</ser:getLoadedRules>"
						+ "</soapenv:Body>" + "</soapenv:Envelope>";

				StringEntity soapEntiry;

				soapEntiry = new StringEntity(body, HTTP.UTF_8);

				postRequest.setEntity(soapEntiry);
				HttpResponse response = client.execute(postRequest);

				if (response.getStatusLine().getStatusCode() == 200) {
					
					InputStream responseIS = response.getEntity().getContent();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(responseIS));
					String line = reader.readLine();
					while (line != null) {
						if (interactive) {
							getWindow().showNotification(
									SessionData.getI18N().getMessage(
											Constants.SUCCESS_LOADEDRULES_WS));
						}
						LOG.info("SOAP LOADEDRULES RESPONSE:" + line);

						List<nl.infodation.emr.pricingservice.data.Item> items = getItemValues(line);
						if (markLoaded) {
							this.markLoadedItems(items);
						} else if (interactive) {
							showLoadedRulesPopup(items);
						}
						line = reader.readLine();
					}
				} else {
					if (interactive) {
						getWindow().showNotification(
								SessionData.getI18N().getMessage(
										Constants.ERROR_LOADEDRULES_WS));
					}
					return Boolean.FALSE;
				}

			} catch (URISyntaxException uriSyntaxException) {
				LOG.warn(String.format(
						"Web service address(\"%s\") is invalid", address),
						uriSyntaxException);
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.WS_ADDRESS_INVALID));
			} catch (UnsupportedEncodingException unsupportedEncodingException) {
				LOG.error("The charset is not supported",
						unsupportedEncodingException);
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.ERROR_RELOAD_WS));
			} catch (ClientProtocolException clientProtocolException) {
				LOG.error("Error sending request to web service",
						clientProtocolException);
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.ERROR_RELOAD_WS));
			} catch (IOException | SOAPException e) {
				LOG.error("Failed reading response content", e);
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.ERROR_RELOAD_WS));
			}
		}
		return Boolean.TRUE;
	}

	private void markLoadedItems(
			List<nl.infodation.emr.pricingservice.data.Item> items) {
		List<Long> activeList = DomainRuleList.getActiveList();
		for (nl.infodation.emr.pricingservice.data.Item item : items) {
			DomainRule rule = BusinessFactory.getRuleBusiness()
					.findRuleByNameAndCheck(item.getValue(),
							SessionData.getEnvironment(),
							SessionData.getRoleName());
			if (rule != null && !activeList.contains(rule.getDomainRuleId())
					&& rule.getPromotionActive() == true) {
				activeList.add(rule.getDomainRuleId());
			}
		}
	}

	private List<nl.infodation.emr.pricingservice.data.Item> getItemValues(
			String soapMessage) throws SOAPException, IOException {
		List<nl.infodation.emr.pricingservice.data.Item> values = new ArrayList<nl.infodation.emr.pricingservice.data.Item>();
		MessageFactory factory = MessageFactory.newInstance();
		SOAPMessage msg = factory.createMessage(
				new MimeHeaders(),
				new ByteArrayInputStream(soapMessage.getBytes(Charset
						.forName("UTF-8"))));
		msg.saveChanges();
		SOAPBody soapBody = msg.getSOAPBody();

		for (Element result : elements(soapBody.getElementsByTagName("result"))) {
			List<Element> items = elements(result.getChildNodes());
			for (Element item : items) {
				String itemValue = item.getTextContent();
				nl.infodation.emr.pricingservice.data.Item i = new nl.infodation.emr.pricingservice.data.Item();
				i.setValue(itemValue);
				values.add(i);
			}
		}

		return values;
	}

	private List<Element> elements(NodeList nodes) {
		List<Element> result = new ArrayList<Element>(nodes.getLength());
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i);
			if (node instanceof Element)
				result.add((Element) node);
		}
		return result;
	}

	private boolean doPublish2Prod(List<String> selectCountries) {
		if (this.executeShowLoadedRules(Boolean.TRUE, Boolean.FALSE,
				selectCountries)) {
			if (this.executeDeployCheckedRules(Boolean.FALSE)
					&& this.executeCopyToProdEnv(Boolean.FALSE, Boolean.TRUE)) {
				this.executeScript(selectCountries);
				this.navigateToProdEnv();
				if (this.executeReloadRule(selectCountries)) {
					// countries = selectCountries;
					return Boolean.TRUE;
				}
			}
		}
		return Boolean.FALSE;
	}

	private boolean checkLoadedRulesOnAtlashServicesBeforPublish(
			List<Long> domainRuleIds, List<String> countries) {
		executeReloadRule(countries);
		if (domainRuleIds.size() < getLoadedRulesPublishing(countries)) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	private boolean checkLoadedRulesOnAtlashServicesAfterPublish(
			List<Long> domainRuleIds, List<String> countries) {
		executeReloadRule(countries);
		if (domainRuleIds.size() > getLoadedRulesPublishing(countries)) {
			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	private boolean doPublish(List<String> countries) {
		if (this.executeShowLoadedRules(Boolean.TRUE, Boolean.FALSE, countries)) {
			if (this.executeDeployCheckedRules(Boolean.FALSE)) {
				if (this.executeReloadRule(countries)) {
					return Boolean.TRUE;
				}
			}
		}
		return Boolean.FALSE;
	}

	private List<String> getCountryListFromCheckedRules() {
		List<DomainRule> domainRules = BusinessFactory.getRuleBusiness()
				.findRulesByIDs(DomainRuleList.getActiveList());
		Set<String> countries = new HashSet<>();
		for (DomainRule domainRule : domainRules) {
			countries.add(domainRule.getCountry());
		}
		return new ArrayList<>(countries);
	}

	private boolean checkExistDomain(List<Long> checkedboxDomains) {
		List<DomainRule> domainRules = BusinessFactory.getRuleBusiness()
				.findRulesByIDs(checkedboxDomains);

		for (DomainRule domainRule : domainRules) {
			if (!domainRule.getPromotionActive()) {
				return Boolean.FALSE;
			}
		}
		return Boolean.TRUE;
	}

	private void doPublishAndWarning() {
		if (doPublish(countries)) {
			if (checkLoadedRulesOnAtlashServicesAfterPublish(
					checkedDomainRuleIds, countries)) {
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.AFTER_PUBLISHED_WARNING),
						Notification.TYPE_WARNING_MESSAGE);
			}
		}
		ReloadSearching();
	}

	@SuppressWarnings("serial")
	private void actionForPublish() {
		if (SessionData.getEnvironment() == Constants.PROD_ENVIROMENT) {
			this.confirmAction(Constants.CONFIRM_DEPLOY_RULES_MESSAGE,
					new ConfirmDialog.Listener() {
						public void onClose(ConfirmDialog dialog) {
							if (dialog.isConfirmed()) {
								doPublishAndWarning();
							}
						}
					});
		} else {
			boolean unExistDomain = checkExistDomain(checkedDomainRuleIds);
			if (unExistDomain == false) {
				this.confirmAction(Constants.UNEXISTRULE,
						new ConfirmDialog.Listener() {
							public void onClose(ConfirmDialog dialog) {
								if (dialog.isConfirmed()) {
									reload();
								}
							}
						});
			} else {
				if (checkLoadedRulesOnAtlashServicesBeforPublish(
						checkedDomainRuleIds, countries)) {
					getWindow().showNotification(
							SessionData.getI18N().getMessage(
									Constants.BEFORE_PUBLISHED_WARNING),
							Notification.TYPE_WARNING_MESSAGE);
					doPublishAndWarning();
				} else {
					doPublishAndWarning();
				}
			}
		}
	}

	@SuppressWarnings("serial")
	private void doPublishProAndWarning() {
		this.confirmAction(Constants.CONFIRM_DEPLOY_RULES_MESSAGE,
				new ConfirmDialog.Listener() {
					public void onClose(ConfirmDialog dialog) {
						if (dialog.isConfirmed()) {
							if (checkLoadedRulesOnAtlashServicesBeforPublish(
									checkedDomainRuleIds, countries)) {
								getWindow()
										.showNotification(
												SessionData
														.getI18N()
														.getMessage(
																Constants.BEFORE_PUBLISHED_WARNING),
												Notification.TYPE_WARNING_MESSAGE);
							}
							if (doPublish2Prod(countries)) {
								if (checkLoadedRulesOnAtlashServicesAfterPublish(
										checkedDomainRuleIds, countries)) {
									getWindow()
											.showNotification(
													SessionData
															.getI18N()
															.getMessage(
																	Constants.AFTER_PUBLISHED_WARNING),
													Notification.TYPE_WARNING_MESSAGE);
								}
							}
							ReloadSearching();
						}
					}
				});
	}

	@SuppressWarnings("serial")
	private void actionForPublish2Pro() {
		boolean unExistDomain = checkExistDomain(checkedDomainRuleIds);
		if (unExistDomain == false) {
			this.confirmAction(Constants.UNEXISTRULE,
					new ConfirmDialog.Listener() {
						public void onClose(ConfirmDialog dialog) {
							if (dialog.isConfirmed()) {
								reload();
							}
						}
					});
		} else {
			doPublishProAndWarning();
		}
	}

	/**
	 * Step 1 : Unchecked the checked all items. Step 2 : Reload Rule list by
	 * the searching data.
	 */
	public void ReloadSearching() {
		// Step 1
		chbCheckAll.setValue(Boolean.FALSE);
		isCheckAll = Boolean.FALSE;
		initialFunctionClear();

		// Step 2
		DomainRuleSearchItem searchIt = prepareSearchItem();
		updateListBySearching(model.getCurrentPage(), searchIt);
		setEnableCheckedRule(Boolean.FALSE);
	}

	@Override
	public void buttonClick(ClickEvent event) {

		SystemValueRefController con = new SystemValueRefController();
		con.getTotalNumberItemByCriteria(new SystemValueRef());

		final Button source = event.getButton();
		if (source == btnPublish) {
			LOG.info(new StringBuilder(DateTimeUtil.getNow()).append(
					" Publish button is clicked.").toString());
			// checkbox countries list
			countries = getCountryListFromCheckedRules();
			checkedDomainRuleIds = DomainRuleList.getActiveList();
			actionForPublish(); // doPublishAndWarning() -> ReloadSearching()
		} else if (source == btnPublishToProd) {
			LOG.info(new StringBuilder(DateTimeUtil.getNow()).append(
					" Publish to Prod button is clicked.").toString());
			countries = getCountryListFromCheckedRules();
			checkedDomainRuleIds = DomainRuleList.getActiveList();
			actionForPublish2Pro(); // -> ReloadSearching()
		} else if (source == btnEdit) {
			LOG.info(new StringBuilder(DateTimeUtil.getNow())
					.append(DateTimeUtil.getNow())
					.append(" Load button is clicked. Load a rule chosen")
					.toString());
			executeLoad();
		} else if (source == btnAdd) {
			LOG.info(new StringBuilder(DateTimeUtil.getNow())
					.append(DateTimeUtil.getNow())
					.append(" Add button is clicked. Add a new rule")
					.toString());
			executeAdd();
		} else if (source == btnSearch) {
			LOG.info(new StringBuilder(DateTimeUtil.getNow())
					.append(DateTimeUtil.getNow())
					.append(" Search button is clicked. Search with criteria in filter")
					.toString());
			searchItem = prepareSearchItem();
			executeSearch(searchItem, PagingModel.FIRST_PAGE);

		} else if (source == btnDuplicate) {
			LOG.info(new StringBuilder(DateTimeUtil.getNow())
					.append(DateTimeUtil.getNow())
					.append(" Duplicate button is clicked. Get the rule as the template for add a new rule")
					.toString());
			executeDuplicate();

		} else if (source == btnDeactive) {
			LOG.info(new StringBuilder(DateTimeUtil.getNow())
					.append(DateTimeUtil.getNow())
					.append(" Remove button is clicked. Remove the checked rules")
					.toString());
			executeRemove();

		} else if (source == btnDeployAllRules) {
			LOG.info(new StringBuilder(DateTimeUtil.getNow())
					.append(DateTimeUtil.getNow())
					.append(" DeployAllRules button is clicked. Generate all rules")
					.toString());
			confirmDeploy(CONFIRM_DEPLOY_ALL_RULES);

		} else if (source == btnDeployCheckedRules) {
			LOG.info(DateTimeUtil.getNow()
					+ "DeployCheckedRules button is clicked. Generate all rules");
			// confirm deploy checked rules
			confirmDeploy(CONFIRM_DEPLOY_CHECKED_RULES);

		} else if (source == btnSwitchToUAT) {
			// Do something when button "Switch to UAT" is clicked
			LOG.info(DateTimeUtil.getNow()
					+ "SwitchToUAT button is clicked. Switch to UAT environment");
			executeSwitchToUAT();

		} else if (source == btnSwitchToPREPROD) {
			// Do something when button "Switch to PRE PROD" is clicked
			LOG.info(DateTimeUtil.getNow()
					+ "SwitchToPREPROD button is clicked. Switch to PREPROD environment");
			executeSwitchToPREPROD();

		} else if (source == btnSwitchToPROD) {
			// Do something when button "Switch to PROD" is clicked
			LOG.info(DateTimeUtil.getNow()
					+ "SwitchToPROD button is clicked. Switch to PROD environment");
			executeSwitchToPROD();

		} else if (source == btnCopyToPreProdEnv) {
			// Do something when button "Copy to PROD environment" is clicked
			LOG.info(DateTimeUtil.getNow()
					+ "CopyToPreProdEnv button is clicked. Copy the checked rules to PREPROD environment");
			executeCopyToPreProdEnv();

		} else if (source == btnCopyToProdEnv) {
			// Do something when button "Copy to PRE PROD environment" is
			// clicked
			LOG.info(DateTimeUtil.getNow()
					+ "CopyToProdEnv button is clicked. Copy the checked rules to PROD environment");
			executeCopyToProdEnv(true, false);

		} else if (source == btnReloadRule) {
			// Do something when button "Reload Rule" is clicked
			LOG.info(DateTimeUtil.getNow()
					+ "Reload button is clicked. Send request to the pricing service address");
			showCountriesChooserPopup(Constants.ACTION_RELOAD_RULES);

		} else if (source == btnShowLoadedRules) {
			// Do something when button "Show Loaded Rules" is clicked
			LOG.info(DateTimeUtil.getNow()
					+ "Show Loaded Rules button is clicked. Send request to the pricing service address and receive a item list.");
			showCountriesChooserPopup(Constants.ACTION_SHOW_LOADED_RULES);
		} else if (source == btnRollBack) {
			LOG.info("buttin Rollback Rule Clicked................");
			executeRoleBackRule();
		} else if (source == btnMarkLoaded) {
			LOG.info(DateTimeUtil.getNow()
					+ "Mark Loaded Rules button is clicked. Send request to the pricing service address and receive a rules list and mark equivalent.");
			showCountriesChooserPopup(Constants.ACTION_MARK_LOADED);

		} else if (source == chbCheckAll) {
			// Do something when check box "Check all" is changed
			isCheckAll = event.getButton().booleanValue();

			// Show log
			if (isCheckAll) {
				LOG.info(DateTimeUtil.getNow() + "Check all rules");
			} else {
				LOG.info(DateTimeUtil.getNow() + "Uncheck all rules");
			}

			ExplicitPagingContainer container = (ExplicitPagingContainer) domainRuleList
					.getContainerDataSource();
			for (int itemId = 0; itemId < container.getItemCount(); itemId++) {

				// Set value for check box
				Item item = container.getItem(itemId);
				Property choiseProperty = item.getItemProperty("choise");
				choiseProperty.setValue(isCheckAll);
			}

			if (isSearching) {
				checkAllForSearching(isCheckAll);
			} else {
				checkAllForTheRuleNoOutOfDate(isCheckAll);
			}

			// Set show/hide actions on screen for user clear
			setEnableCheckedRule(isCheckAll);
		}
	}

	private void checkAllForTheRuleNoOutOfDate(boolean isCheckAll) {
		DomainRuleSearchItem searchItem = new DomainRuleSearchItem();
		searchItem.setTodayDate(new Date());
		searchItem.setEnvironmentId(SessionData.getEnvironment());
		searchItem.setPromotionActive(Boolean.TRUE);
		List<Long> IDs = BusinessFactory.getRuleBusiness().searchRulesIDs(
				searchItem);
		checkAllRules(isCheckAll, IDs);
	}

	private void checkAllForSearching(boolean isCheckAll) {
		DomainRuleSearchItem searchItem = prepareSearchItem();
		searchItem.setEnvironmentId(SessionData.getEnvironment());
		List<Long> IDs = BusinessFactory.getRuleBusiness().searchRulesIDs(
				searchItem);
		checkAllRules(isCheckAll, IDs);
	}

	/**
	 * @param isCheckAll
	 * @param beans
	 */
	public void checkAllRules(boolean isCheckAll, final List<Long> IDs) {
		DomainRuleList.getActiveList().clear();
		if (isCheckAll) {
			DomainRuleList.getActiveList().addAll(IDs);
		}
	}

	public List<String> getCountriesFromCountryCheckerList() {
		return CountryCheckerList.getActiveList();
	}

	public void rollBackRule(PublishedHistory publishedDomain) {
		DomainRule domain = publishedDomain.getDomainRule();
		parentView.showDetail();
		parentView.setDetailView(domain, true);
	}

	private void executeRoleBackRule() {
		if (domainRulePopup == null) {
			// Show "select" popup
			if (curDomainRule == null) {
				getWindow().showNotification(
						SessionData.getI18N().getMessage(
								Constants.CHECKROLLBACK));
			} else {
				boolean userCheck = checkUserRollBack(curDomainRule);

				if (userCheck == true) {
					final Window w = new Window();
					w.setCaption(SessionData.getI18N().getMessage(
							Constants.HISTORY)
							+ " "
							+ curDomainRule.getRuleName()
							+ " "
							+ SessionData.getI18N().getMessage(Constants.RULE));
					getApplication().getMainWindow().addWindow(w);

					domainRulePopup = new DomainRulePopup(this, curDomainRule);
					domainRulePopup.setSizeFull();
					w.addListener(new Window.CloseListener() {
						private static final long serialVersionUID = 1L;

						@Override
						public void windowClose(CloseEvent e) {
							if (e.getSource() == w) {
								domainRulePopup = null;
							}
						}
					});
					w.setContent(domainRulePopup);
					w.setWidth(350, Window.UNITS_PIXELS);
					w.setHeight(600, Window.UNITS_PIXELS);
					w.center();
				} else {
					getWindow().showNotification(
							SessionData.getI18N().getMessage(
									Constants.PERMISSIONROLLBACK));
				}
			}
		}
	}

	private boolean checkUserRollBack(DomainRule rule) {
		boolean userRole = Boolean.TRUE;
		String businnesUser = SessionData.getRoleName();
		List<SystemValue> userContries = SessionData.getCountriesToSee();
		if (SessionData.isSuperAdmin()) {
			return userRole;
		} else if (SessionData.isNormalAdmin()) {
			if (businnesUser.equals(rule.getBusLine())) {
				userRole = Boolean.TRUE;
			} else {
				userRole = Boolean.FALSE;
			}
			return userRole;
		} else {
			if (businnesUser.equals(rule.getBusLine())) {
				for (SystemValue country : userContries) {
					String countryCode = country.getSystemCode();
					if (countryCode.equals(rule.getCountry())) {
						userRole = Boolean.TRUE;
						break;
					}
				}
			} else {
				userRole = Boolean.FALSE;
			}
		}
		return userRole;
	}

	private void showCountriesChooserPopup(String action) {
		if (countryCheckerPopup == null) {
			// Disable main view when using popup "countryChecker"
			if (this.getApplication().getContext() instanceof MainView) {
				((MainView) this.getApplication().getContext())
						.setEnabled(Boolean.FALSE);
			}
			
			UserCountryCheckerList.getActiveList().clear();

			// Show "select" popup
			final Window w = new Window();
			w.setCaption(SessionData.getI18N().getMessage(
					Constants.COUNTRY_CHECK));
			getApplication().getMainWindow().addWindow(w);

			countryCheckerPopup = new CountryCheckerPopup(this, action);
			countryCheckerPopup.setSizeFull();
			countryCheckerPopup.setCaption(SessionData.getI18N().getMessage(
					Constants.PROMOTION_CONNECTED_SELECTION_POPUP));

			w.addListener(new Window.CloseListener() {
				private static final long serialVersionUID = 1L;

				// Close-listener
				public void windowClose(CloseEvent e) {
					if (e.getSource() == w) {
						countryCheckerPopup = null;
						UserCountryCheckerList.getActiveList().clear();
						// userLayout.setEnabled(Boolean.TRUE);
					}
				}
			});
			w.setContent(countryCheckerPopup);
			w.setWidth(303, Window.UNITS_PIXELS);
			w.setHeight(411, Window.UNITS_PIXELS);
			w.center();
		}
	}

	private void executeScript(List<String> selectedCountries) {
		EntityManager entityManager = null;
		try {
			entityManager = EM_FACTORY.createEntityManager();
			Connector connector = new Connector();
			String entity = "";
			String roleName = SessionData.getRoleName();
			if (Constants.PROVEA_ROLE.equals(roleName)) {
				entity = Constants.PROVEA_SCRIPT_PATH;

			} else if (Constants.AFM_ROLE.equals(roleName)) {
				entity = Constants.AFM_SCRIPT_PATH;

			} else {
				String bus = SessionData.getDeploymentRoleName();
				if (Constants.PROVEA_ROLE.equals(bus)) {
					entity = Constants.PROVEA_SCRIPT_PATH;

				} else if (Constants.AFM_ROLE.equals(bus)) {
					entity = Constants.AFM_SCRIPT_PATH;

				}
			}
			String script = connector.getConfig(entity, entityManager);
			File execFile = new File(script);
			if (execFile.exists()) {
				try {
					File dir = execFile.getParentFile();
					List<String> scriptWithParams = addParamsToScriptCommand(script, selectedCountries);
					ProcessBuilder pb = new ProcessBuilder(scriptWithParams);
					pb.directory(dir);
					LOG.info("Run:" + scriptWithParams);
					final Process process = pb.start();
					process.waitFor();

					getWindow().showNotification(
							SessionData.getI18N().getMessage(
									Constants.RUN_SCRIPT_SUCCESS));
				} catch (InterruptedException ie) {
					LOG.error("Error when execute script", ie);
				}
			}
		} catch (IOException e) {
			LOG.error("Error when execute script", e);
			getWindow()
					.showNotification(
							SessionData.getI18N().getMessage(
									Constants.RUN_SCRIPT_FAIL));
		} finally {
			if (entityManager != null && entityManager.isOpen()) {
				entityManager.close();
			}
		}
	}

	private List<String> addParamsToScriptCommand(String script,
			List<String> countries) {
		List<String> scriptRun = new ArrayList<String>();
		scriptRun.add(script);
		if (null != countries && !countries.isEmpty()) {
			for (String countryCode : countries) {
				if (!StringUtil.isEmptyOrBlank(countryCode)) {
					scriptRun.add(countryCode.toLowerCase());
				}
			}
		}
		return scriptRun;
	}
	
	private LoadedRulesPopup loadedRulesPopup;

	private void showLoadedRulesPopup(
			List<nl.infodation.emr.pricingservice.data.Item> items) {
		if (loadedRulesPopup == null) {
			final Window w = new Window();
			getApplication().getMainWindow().addWindow(w);

			loadedRulesPopup = new LoadedRulesPopup(items);
			loadedRulesPopup.setSizeFull();
			loadedRulesPopup.setCaption(SessionData.getI18N().getMessage(
					Constants.LOADED_RULES_POPUP));

			w.addListener(new Window.CloseListener() {
				private static final long serialVersionUID = 1L;

				// Close-listener
				public void windowClose(CloseEvent e) {
					if (e.getSource() == w) {
						loadedRulesPopup = null;
					}
				}
			});

			w.setContent(loadedRulesPopup);
			w.setWidth(800, Window.UNITS_PIXELS);
			w.setHeight(660, Window.UNITS_PIXELS);
		}
	}

	public void setEnableCheckedRule(boolean enabled) {
		setRemoveButtonEnable(enabled);
		setDeployCheckedRulesButtonEnable(enabled);
		setCopyToPreProdButtonEnable(enabled);
		setCopyToProdButtonEnable(enabled);
		setPublishButtonEnable(enabled);
		setPublishToProdButtonEnable(enabled);
		setEnableDupplicateAndLoad();

	}

	private void setEnableDupplicateAndLoad() {
		setDuplicateButtonEnable(Boolean.TRUE);
		setLoadButtonEnable(Boolean.TRUE);
	}

	public void setEnableChosenRule(boolean enabled) {
		setLoadButtonEnable(enabled);
		setDuplicateButtonEnable(enabled);
	}

	public void setLoadButtonEnable(boolean enabled) {
		this.btnEdit.setEnabled(enabled);
	}

	public void setDuplicateButtonEnable(boolean enabled) {
		this.btnDuplicate.setEnabled(enabled);
	}

	public void setPublishToProdButtonEnable(boolean enabled) {
		this.btnPublishToProd.setEnabled(enabled);
	}

	public void setPublishButtonEnable(boolean enabled) {
		this.btnPublish.setEnabled(enabled);
	}

	public void setRemoveButtonEnable(boolean enabled) {
		this.btnDeactive.setEnabled(enabled);
	}

	public void setDeployCheckedRulesButtonEnable(boolean enabled) {
		this.btnDeployCheckedRules.setEnabled(enabled);
	}

	public void setCopyToPreProdButtonEnable(boolean enabled) {
		this.btnCopyToPreProdEnv.setEnabled(enabled);
	}

	public void setCopyToProdButtonEnable(boolean enabled) {
		this.btnCopyToProdEnv.setEnabled(enabled);
	}

	private void setFormatDateField() {
		tfFromDate.setDateFormat("dd-MM-yyyy");
		tfToDate.setDateFormat("dd-MM-yyyy");
	}

	private void executeSearch(DomainRuleSearchItem searchItem, int page) {
		isSearching = Boolean.TRUE;
		model.setCurrentPage(page);

		updateListBySearching(page, searchItem);
	}

	private DomainRuleSearchItem getSearchItem() {
		DomainRuleSearchItem searchItem = new DomainRuleSearchItem();
		searchItem.setPromoCode((String) tfPromoCode.getValue());
		searchItem.setRuleName((String) tfRuleName.getValue());
		searchItem.setBusLine((String) cbbBusLine.getValue());
		searchItem.setLanguage((String) tfLanguage.getValue());
		searchItem.setCountry((String) cbbCountry.getValue());
		searchItem.setFromDate((Date) tfFromDate.getValue());
		searchItem.setToDate((Date) tfToDate.getValue());

		boolean showAllRules = BooleanUtil
				.getValueWithoutNull((Boolean) chbShowAllRules.getValue());
		if (!showAllRules) {
			searchItem.setTodayDate(new Date());
		}

		// search active Rule
		searchItem.setPromotionActive(Boolean.TRUE);

		return searchItem;
	}

	@SuppressWarnings("rawtypes")
	private void updateListBySearching(final int page,
			DomainRuleSearchItem searchItem) {
		searchItem.setPromotionActive(Boolean.TRUE);
		SearchResult<BeanItem> result = BusinessFactory.getRuleBusiness()
				.searchRules(SessionData.getRoleName(),
						SessionData.getEnvironment(), searchItem, page,
						domainRuleList.getPageSize());
		domainRuleList.setDataSource(result.getResult());

		final int totalPages = (int) Math.ceil(result.getTotalCount()
				/ (float) domainRuleList.getPageSize());
		model.setTotalNumberOfPages(totalPages);
		model.setCurrentPage(page);
		updatePageNumber();
	}

	private DomainRuleSearchItem prepareSearchItem() {
		DomainRuleSearchItem searchItem = getSearchItem();
		if (Constants.ALL_FOR_SEARCH.equals(searchItem.getBusLine())) {
			searchItem.setBusLine("");
		}
		if (Constants.ALL_FOR_SEARCH.equals(searchItem.getCountry())) {
			searchItem.setCountry("");
		}

		return searchItem;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void itemClick(ItemClickEvent event) {
		LOG.info(DateTimeUtil.getNow() + "Choose a rule");
		BeanItem bean = (BeanItem) event.getItem();
		curDomainRule = (DomainRule) bean.getBean();
		setEnableChosenRule(Boolean.TRUE);

		if (event.isDoubleClick()) {
			LOG.info(DateTimeUtil.getNow()
					+ "Double click a rule. Loading the rule");
			parentView.showDetail();
			parentView.setDetailView(curDomainRule, true);
		}
	}

	Panel btnPanel;
	CustomLayout buttonCustomLayout;

	private Panel initButtonCustomLayout() {
		buttonCustomLayout = new CustomLayout("showButtonOption");

		buttonCustomLayout.addComponent(btnReloadRule, "lcBtnReload");
		buttonCustomLayout.addComponent(btnMarkLoaded, "lcBtnMarkLoaded");
		buttonCustomLayout.addComponent(btnDeployCheckedRules,
				"lcBtnDeployCheckedRules");
		buttonCustomLayout.addComponent(btnDeployAllRules,
				"lcBtnDeployAllRules");

		buttonCustomLayout.addComponent(new Label(SessionData.getI18N()
				.getMessage(Constants.DEPLOY_ALL_RULES_BUTTON)),
				"lcTipDeployAllRules");
		buttonCustomLayout.addComponent(new Label(SessionData.getI18N()
				.getMessage(Constants.DEPLOY_CHECKED_RULES_BUTTON)),
				"lcTipDeployCheckedRules");
		buttonCustomLayout.addComponent(new Label(SessionData.getI18N()
				.getMessage(Constants.RELOAD_BUTTON)), "lcTipReload");
		buttonCustomLayout.addComponent(new Label(SessionData.getI18N()
				.getMessage(Constants.MARK_LOADED_RULES_BUTTON)),
				"lcTipMarkLoaded");
		buttonCustomLayout.addComponent(new Label(SessionData.getI18N()
				.getMessage(Constants.SCRIPT_BUTTON)), "lcTipExecuteScript");

		btnPanel = new Panel(buttonCustomLayout);
		btnPanel.setStyleName("buttonOption");
		return btnPanel;
	}

	@AutoGenerated
	private void buildMainLayout() {

		ActivePromotionsCustomLayout = new CustomLayout("ActivePromotions");

		btnDeployAllRules = new NativeButton();
		btnDeployAllRules.setStyleName("right_button");
		btnDeployAllRules.addStyleName("alldeploy");

		btnDeployCheckedRules = new NativeButton();
		btnDeployCheckedRules.setStyleName("right_button");
		btnDeployCheckedRules.addStyleName("checkdeploy");

		btnReloadRule = new NativeButton();
		btnReloadRule.setStyleName("right_button");
		btnReloadRule.addStyleName("reload");

		btnMarkLoaded = new NativeButton();
		btnMarkLoaded.setStyleName("right_button");
		btnMarkLoaded.addStyleName("markloaded");

		pagingComponent = new PagingComponent();
		pagingComponent.setImmediate(Boolean.FALSE);
		pagingComponent.setStyleName("inline");
		ActivePromotionsCustomLayout.addComponent(pagingComponent, "lcPage");

		lblCurrentPage = new Label();
		lblCurrentPage.setImmediate(Boolean.FALSE);
		lblCurrentPage.setStyleName("inline");
		lblCurrentPage.setValue("Current Page: ?");
		ActivePromotionsCustomLayout.addComponent(lblCurrentPage,
				"lcCurrentPage");

		domainRuleList = new DomainRuleList();
		domainSetting = getDomainListSetting();
		domainRuleList.setColumWidth(domainSetting);
		domainRuleList.setImmediate(Boolean.TRUE);
		domainRuleList.setColumnCollapsingAllowed(Boolean.TRUE);
		domainRuleList.setSizeFull();
		domainRuleList.setWidth("736px");
		domainRuleList.setHeight("700px");
		ActivePromotionsCustomLayout.addComponent(domainRuleList,
				"lcTableListRules");
		lblEnvironmentName = new Label();
		lblEnvironmentName.setImmediate(Boolean.TRUE);
		lblEnvironmentName.setStyleName("inline");
		ActivePromotionsCustomLayout.addComponent(lblEnvironmentName, "lblEnv");

		chbCheckAll = new CheckBox();
		chbCheckAll.setImmediate(Boolean.TRUE);
		chbCheckAll.setCaption("Check all");
		chbCheckAll.setStyleName("simple");
		ActivePromotionsCustomLayout.addComponent(chbCheckAll, "lcCheckAll");

		lblBusiness = new Label();
		lblBusiness.setStyleName("captionLabel");
		lblBusiness.setImmediate(Boolean.FALSE);
		lblBusiness.setValue("Business:");

		lblBusinessLine = new Label();
		lblBusinessLine.setImmediate(Boolean.FALSE);

		// Filter
		tfPromoCode = new TextField();
		tfPromoCode.setStyleName("inline");
		ActivePromotionsCustomLayout.addComponent(tfPromoCode, "lcPromoCode");

		tfRuleName = new TextField();
		tfRuleName.setStyleName("inline");
		ActivePromotionsCustomLayout.addComponent(tfRuleName, "lcRuleName");

		cbbBusLine = new ComboBox();
		cbbBusLine.setImmediate(Boolean.FALSE);
		cbbBusLine.setStyleName("inline");
		cbbBusLine.setWidth(106, ComboBox.UNITS_PIXELS);
		cbbBusLine.setHeight(23, ComboBox.UNITS_PIXELS);
		ActivePromotionsCustomLayout.addComponent(cbbBusLine, "lcBusLine");

		tfLanguage = new TextField();
		tfLanguage.setStyleName("inline");
		ActivePromotionsCustomLayout.addComponent(tfLanguage, "lcLanguage");

		cbbCountry = new ComboBox();
		cbbCountry.setImmediate(Boolean.FALSE);
		cbbCountry.setStyleName("inline");
		cbbCountry.setWidth(106, ComboBox.UNITS_PIXELS);
		cbbCountry.setHeight(23, ComboBox.UNITS_PIXELS);
		ActivePromotionsCustomLayout.addComponent(cbbCountry, "lcCountry");

		tfFromDate = new PopupDateField();
		tfFromDate.setInvalidAllowed(Boolean.FALSE);
		tfFromDate.setStyleName("inline");
		ActivePromotionsCustomLayout.addComponent(tfFromDate, "lcFromDate");

		tfToDate = new PopupDateField();
		tfToDate.setInvalidAllowed(Boolean.FALSE);
		tfToDate.setStyleName("inline");
		ActivePromotionsCustomLayout.addComponent(tfToDate, "lcToDate");

		chbShowAllRules = new CheckBox();
		chbShowAllRules.setCaption("Show All Rules");
		chbShowAllRules.setStyleName("inline");
		ActivePromotionsCustomLayout.addComponent(chbShowAllRules,
				"lcShowAllRule");

		btnSearch = new NativeButton();
		btnSearch.setStyleName("small_button");
		ActivePromotionsCustomLayout.addComponent(btnSearch, "lcBtnSearch");

		// Right buttons
		btnPublish = new NativeButton();
		btnPublish.setStyleName("right_button");
		btnPublish.addStyleName("publish");
		ActivePromotionsCustomLayout.addComponent(btnPublish, "lcBtnPublish");

		btnPublishToProd = new NativeButton();
		btnPublishToProd.setStyleName("right_button");
		btnPublishToProd.addStyleName("publishtoprod");
		ActivePromotionsCustomLayout.addComponent(btnPublishToProd,
				"lcBtnPublishToProd");

		btnEdit = new NativeButton();
		btnEdit.setCaption("Load");
		btnEdit.setStyleName("right_button");
		btnEdit.addStyleName("load");
		btnEdit.setImmediate(Boolean.TRUE);
		ActivePromotionsCustomLayout.addComponent(btnEdit, "lcBtnLoad");

		btnAdd = new NativeButton();
		btnAdd.setStyleName("right_button");
		btnAdd.addStyleName("new");
		ActivePromotionsCustomLayout.addComponent(btnAdd, "lcBtnAddNew");

		btnRollBack = new NativeButton();
		btnRollBack.setStyleName("right_button");
		btnRollBack.addStyleName("rollback");
		ActivePromotionsCustomLayout.addComponent(btnRollBack, "lcBtnRollBack");

		btnDuplicate = new NativeButton();
		btnDuplicate.setStyleName("right_button");
		btnDuplicate.addStyleName("duplicate");
		ActivePromotionsCustomLayout.addComponent(btnDuplicate,
				"lcBtnDuplicateRule");

		btnDeactive = new NativeButton();
		btnDeactive.setStyleName("right_button");
		btnDeactive.addStyleName("remove");
		ActivePromotionsCustomLayout.addComponent(btnDeactive, "lcBtnDeactive");

		btnShowLoadedRules = new NativeButton();
		btnShowLoadedRules.setStyleName("right_button");
		btnShowLoadedRules.addStyleName("show");
		ActivePromotionsCustomLayout.addComponent(btnShowLoadedRules,
				"lcBtnShowLoadedRules");

		btnSwitchToPREPROD = new NativeButton();
		btnSwitchToPREPROD.setStyleName("right_button");
		btnSwitchToPREPROD.addStyleName("switchtopreprod");
		ActivePromotionsCustomLayout.addComponent(btnSwitchToPREPROD,
				"lcBtnSwitchToPreProd");

		btnSwitchToPROD = new NativeButton();
		btnSwitchToPROD.setStyleName("right_button");
		btnSwitchToPROD.addStyleName("switchtoprod");
		ActivePromotionsCustomLayout.addComponent(btnSwitchToPROD,
				"lcBtnSwitchToProd");

		btnSwitchToUAT = new NativeButton();
		btnSwitchToUAT.setStyleName("right_button");
		btnSwitchToUAT.addStyleName("switchtouat");
		ActivePromotionsCustomLayout.addComponent(btnSwitchToUAT,
				"lcBtnSwitchToUAT");

		btnCopyToPreProdEnv = new NativeButton();
		btnCopyToPreProdEnv.setStyleName("right_button");
		btnCopyToPreProdEnv.addStyleName("copytopreprodenv");
		ActivePromotionsCustomLayout.addComponent(btnCopyToPreProdEnv,
				"lcBtnCopyToPreProdEnv");

		btnCopyToProdEnv = new NativeButton();
		btnCopyToProdEnv.setStyleName("right_button");
		btnCopyToProdEnv.addStyleName("copytoprodenv");
		ActivePromotionsCustomLayout.addComponent(btnCopyToProdEnv,
				"lcBtnCopyToProdEnv");
	}

}
